import win32service
import win32serviceutil
import win32api
import win32con

from twisted.internet import reactor
from twisted.python import log
from ircDivBot import DivBotFactory

class DivBotService(win32serviceutil.ServiceFramework):
    _svc_name_ = "DivBot"
    _svc_display_name_ = "Diversity IRC Bot"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)

    def SvcDoRun(self):
        import servicemanager

##        logfile = open('DivBotLog.txt','w')
##        log.startLogging(logfile)
        servicemanager.LogInfoMsg("DivBot - Starting Client")
        log.msg("DivBot - Starting Client")
        factory = DivBotFactory()
        reactor.connectTCP("irc.utonet.org", 6667, factory)
        reactor.run(installSignalHandlers=0)
        servicemanager.LogInfoMsg("DivBot - Client Stopped")
        log.msg("DivBot - Client Stopped")
        
    def SvcStop(self):
        import servicemanager

        servicemanager.LogInfoMsg("DivBot - Recieved stop signal")
        log.msg("DivBot - Recieved stop signal")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        reactor.callFromThread(reactor.stop)

def ctrlHandler(ctrlType):
    return True

if __name__ == '__main__':
    win32api.SetConsoleCtrlHandler(ctrlHandler, True)
    win32serviceutil.HandleCommandLine(DivBotService)
